package com.beiing.tianshuai.tianshuai.home.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.SearchClassificationDropMenuAdapter;
import com.beiing.tianshuai.tianshuai.adapter.SearchResultAdapter;
import com.beiing.tianshuai.tianshuai.adapter.TextOnlyTagAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.IndexSearchListBean;
import com.beiing.tianshuai.tianshuai.entity.SearchClassifiesBean;
import com.beiing.tianshuai.tianshuai.entity.TopSearchAndClassificationBean;
import com.beiing.tianshuai.tianshuai.freshnews.DiscoveryDetailActivity;
import com.beiing.tianshuai.tianshuai.home.RecordsDao;
import com.beiing.tianshuai.tianshuai.home.presenter.SearchPresenterImpl;
import com.beiing.tianshuai.tianshuai.home.view.ISearchView;
import com.beiing.tianshuai.tianshuai.huodong.ActivitiesDetailActivity;
import com.beiing.tianshuai.tianshuai.interest.InterestVideoDetailActivity;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.hhl.library.FlowTagLayout;
import com.hhl.library.OnTagClickListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Jinda Yang on 2017/12/7.
 * Description:全局搜索界面
 */

public class SearchActivity extends BaseActivity implements ISearchView {

    private static final String TAG = "SearchActivity";

    /**
     * 数据库链接实体
     */
    private RecordsDao mRecordsDao;

    /**
     * presenter
     */
    private SearchPresenterImpl mPresenter;

    /**
     * 搜索结果的adapter
     */
    private SearchResultAdapter mSearchResultAdapter;

    /**
     * 搜索历史标签布局适配器
     */
    private TextOnlyTagAdapter<String> mSearchHistoriesTagLayoutAdapter;

    /**
     * 分类菜单列表适配器
     */
    private SearchClassificationDropMenuAdapter mSearchClassificationDropMenuAdapter;

    /**
     * 搜索分类的drop down menu
     */
    private PopupWindow mPupWindow;

    /**
     * 当前所选中的搜索类别position
     */
    private int mClassifySelectedPosition;

    /**
     * toolbar
     */
    @BindView(R.id.toolbar_container)
    Toolbar mToolbar;

    /**
     * 搜索输入框
     */
    @BindView(R.id.et_search_content)
    EditText mEtSearchContent;

    /**
     * 输入框父布局
     */
    @BindView(R.id.rv_research)
    RelativeLayout mRvResearch;

    /**
     * 清除输入框内容图标
     */
    @BindView(R.id.iv_search_delete)
    ImageView mIvSearchDelete;

    /**
     * 搜索结果列表
     */
    @BindView(R.id.rv_search_result_list)
    RecyclerView mRvSearchResult;

    /**
     * scrollview
     */
    @BindView(R.id.nstScrollView)
    NestedScrollView mScrollView;

    /**
     * 清空搜索历史记录按钮
     */
    @BindView(R.id.tv_delete_all)
    ImageButton mTvDeleteAll;

    /**
     * 热搜标签
     */
    @BindView(R.id.ftl_hot_search)
    FlowTagLayout mFtlHotSearch;

    /**
     * 搜索历史标签
     */
    @BindView(R.id.ftl_search_histories)
    FlowTagLayout mFtlSearchHistories;

    /**
     * 搜索历史标题父布局
     */
    @BindView(R.id.rl_search_history_label_container)
    RelativeLayout mRlSearchHistoryLabelContainer;

    /**
     * 热搜标题
     */
    @BindView(R.id.tv_hot_search_label)
    TextView mTvHotSearchLabel;

    /**
     * 当前搜索分类
     */
    @BindView(R.id.tv_search)
    TextView mClassifyDropDownButton;

    /**
     * 搜索结果空提示
     */
    @BindView(R.id.tv_search_result_empty)
    TextView mTvSearchResultEmpty;

    /**
     * 弹出菜单的半透明背景
     */
    @BindView(R.id.popup_window_background)
    View mPopupWindowBackground;

    /**
     * 取消按钮
     */
    @BindView(R.id.tv_cancel)
    TextView mTvCancel;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void init() {
        mRecordsDao = new RecordsDao(mContext);
        initSearchHistory();
        initRecyclerView();
        initPresenter();
        initPopupWindow();
        initListener();
    }

    private void initPopupWindow() {
        View view = View.inflate(mContext, R.layout.index_search_classify_drop_down_menu, null);
        //第一个参数为要显示的view，后边为popuwindown的宽和高，也可以是具体数值
        mPupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //是否需要获取焦点
        mPupWindow.setFocusable(true);
        //点击外边是否可以取消
        mPupWindow.setOutsideTouchable(true);
        ColorDrawable colorDrawable = new ColorDrawable(ContextCompat.getColor(mContext, R.color.press_mask));
        mPupWindow.setBackgroundDrawable(colorDrawable);
        mPupWindow.setAnimationStyle(R.style.popupAnimation);
        mPupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPopupWindowBackground.setVisibility(View.GONE);
            }
        });
        //在控件V某个位置显示，有LEFT,BOTTOM,TOP。后边是在x方向偏移的距离，和在y方向的偏移的距离
//        mPupWindow.showAtLocation(v, Gravity.RIGHT, location[0], location[1]-popupWindow.getHeight());
        //在控件V正下方显示
//        mPupWindow.showAsDropDown(mToolbar);//在正下方显示

        //设置下拉菜单中的数据信息
        RecyclerView rvClassificationDropDownMenu = view.findViewById(R.id.rv_classifies_menu);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvClassificationDropDownMenu.setLayoutManager(manager);
        rvClassificationDropDownMenu.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0.5f),
                ContextCompat.getColor(mContext, R.color.common_gray_background))
        );
        //设置菜单列表RecyclerView的适配器
        mSearchClassificationDropMenuAdapter = new SearchClassificationDropMenuAdapter(mContext);
        rvClassificationDropDownMenu.setAdapter(mSearchClassificationDropMenuAdapter);
        mSearchClassificationDropMenuAdapter.setOnItemSelectedListener(
                new SearchClassificationDropMenuAdapter.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(List<SearchClassifiesBean> searchClassifiesBeans,
                                               SearchClassifiesBean bean, int position) {
                        searchClassifiesBeans.get(mClassifySelectedPosition).setSelected(false);
                        mClassifySelectedPosition = position;
                        bean.setSelected(true);
                        mSearchClassificationDropMenuAdapter.notifyDataSetChanged();
                        mClassifyDropDownButton.setText(bean.getClassifyName());
                        mPupWindow.dismiss();
                        //如果当前搜索框内已存在关键字则重新请求搜索
                        String keyword = mEtSearchContent.getText().toString();
                        if (!TextUtils.isEmpty(keyword)) {
                            doSearch(keyword);
                        }
                    }
                });
    }

    /**
     * 初始化presenter
     */
    private void initPresenter() {
        mPresenter = new SearchPresenterImpl(this);
        mPresenter.getTopSearchAndClassification();
    }

    /**
     * 初始化搜索历史标签布局
     */
    private void initSearchHistory() {
        List<IndexSearchListBean.DataBean.ResultBean> recordsList = mRecordsDao.getRecordsList();
        final List<String> searchHistories = new ArrayList<>();
        if (!recordsList.isEmpty()) {
            mRlSearchHistoryLabelContainer.setVisibility(View.VISIBLE);
            mFtlSearchHistories.setVisibility(View.VISIBLE);
            for (IndexSearchListBean.DataBean.ResultBean indexSearchListBean : recordsList) {
                searchHistories.add(indexSearchListBean.getTitle());
            }
            mSearchHistoriesTagLayoutAdapter = new TextOnlyTagAdapter<>(mContext);
            mFtlSearchHistories.setAdapter(mSearchHistoriesTagLayoutAdapter);
            mFtlSearchHistories.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_NONE);
            mSearchHistoriesTagLayoutAdapter.appendData(searchHistories);
            mFtlSearchHistories.setOnTagClickListener(new OnTagClickListener() {
                @Override
                public void onItemClick(FlowTagLayout parent, View view, int position) {
                    String searchHistoriesSelected = searchHistories.get(position);
                    mEtSearchContent.setText(searchHistoriesSelected);
                }
            });
        } else {
            mRlSearchHistoryLabelContainer.setVisibility(View.GONE);
            mFtlSearchHistories.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化搜索结果的RecyclerView
     */
    private void initRecyclerView() {
        mSearchResultAdapter = new SearchResultAdapter(mContext);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRvSearchResult.setLayoutManager(linearLayoutManager);
        mRvSearchResult.setAdapter(mSearchResultAdapter);
        mRvSearchResult.addItemDecoration(
                new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0.5f),
                        ContextCompat.getColor(mContext, R.color.common_gray_background))
        );
        mSearchResultAdapter.setOnItemClickListener(new SearchResultAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, IndexSearchListBean.DataBean.ResultBean bean) {
                Intent intent = new Intent();
                switch (bean.getIsNum()) {
                    case "2":
                        intent.setClass(mContext, ActivitiesDetailActivity.class);
                        intent.putExtra("active_id", bean.getId());
                        break;
                    case "3":
                        intent.setClass(mContext, DiscoveryDetailActivity.class);
                        intent.putExtra("fresh_id", bean.getId());
                        break;
                    case "4":
                        intent.setClass(mContext, InterestVideoDetailActivity.class);
                        intent.putExtra("vid", bean.getId());
                        break;
                    default:
                        break;
                }
                mRecordsDao.addRecords(bean);
                startActivity(intent);
                finish();
            }
        });
    }

    /**
     * 设置监听事件
     */
    private void initListener() {
        // 取消按钮
        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(mEtSearchContent.getWindowToken(), 0);
                }
                finish();
            }
        });

        // 搜索分类按钮点击事件 点击弹出分类选择菜单
        mClassifyDropDownButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mPupWindow.isShowing()) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(mEtSearchContent.getWindowToken(), 0);
                    }
                    mPopupWindowBackground.setVisibility(View.VISIBLE);
                    mPupWindow.showAsDropDown(mToolbar);
                } else {
                    mPupWindow.dismiss();
                }
            }
        });

        // 给输入框设置软键盘搜索事件
        mEtSearchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    String keyword = mEtSearchContent.getText().toString();
                    if (!TextUtils.isEmpty(keyword)) {
                        doSearch(keyword);
                        //隐藏软键盘
                        InputMethodManager imm = (InputMethodManager) textView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (imm != null && imm.isActive()) {
                            imm.hideSoftInputFromWindow(textView.getApplicationWindowToken(), 0);
                        }
                        return true;
                    } else {
                        showShortText("请输入关键字");
                    }
                }
                return false;
            }
        });

        // 设置搜索框整体布局的点击事件
        mRvResearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtSearchContent.setFocusable(true);
                mEtSearchContent.setFocusableInTouchMode(true);
            }
        });

        // 设置搜索框输入框的 text change listener
        mEtSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                doSearch(editable.toString());
            }
        });

        // 输入框清空文字按钮的点击事件
        mIvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEtSearchContent.setText("");
                mTvSearchResultEmpty.setVisibility(View.GONE);
            }
        });

        // 清除所有历史
        mTvDeleteAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CustomDialog dialog = new CustomDialog(
                        mContext,
                        R.style.dialog,
                        "确认清空搜索历史？",
                        new CustomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                                if (confirm) {
                                    mRecordsDao.deleteAllRecords();
                                    mSearchHistoriesTagLayoutAdapter.clearAllTags();
                                    mRlSearchHistoryLabelContainer.setVisibility(View.GONE);
                                    dialog.dismiss();
                                } else {
                                    dialog.dismiss();
                                }
                            }
                        }).setNegativeButton("取消").setPositiveButton("确认").setTitle("删除提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        });
    }

    /**
     * 执行搜索请求
     *
     * @param keyword 关键字
     */
    private void doSearch(String keyword) {
        if (!keyword.isEmpty()) {
            mIvSearchDelete.setVisibility(View.VISIBLE);
            List<SearchClassifiesBean> list = mSearchClassificationDropMenuAdapter.getList();
            String classifyId;
            if (!list.isEmpty()) {
                classifyId = list.get(mClassifySelectedPosition).getClassifyId();
            } else {
                classifyId = "1";
            }
            mPresenter.getSearchResult(keyword,
                    Integer.parseInt(classifyId));
        } else {
            mSearchResultAdapter.clearData();
            mScrollView.setVisibility(View.VISIBLE);
            mIvSearchDelete.setVisibility(View.GONE);
            mTvSearchResultEmpty.setVisibility(View.GONE);
        }
    }

    /**
     * 展示热搜词，并设置分类搜索按钮的分类条目
     *
     * @param bean 热搜词和分类
     */
    @Override
    public void getTopSearchAndClassificationSuccess(TopSearchAndClassificationBean bean) {
        // 设置热门搜索tag标签
        List<TopSearchAndClassificationBean.DataBean.SeaHotBean> hotSearchList = bean.getData().getSeaHot();
        if (!hotSearchList.isEmpty()) {
            // 如果热搜词列表不为空 显示热搜标题和FlowTagLayout
            mTvHotSearchLabel.setVisibility(View.VISIBLE);
            mFtlHotSearch.setVisibility(View.VISIBLE);

            // 设置热搜词标签及标签点击事件
            final List<String> hotSearchKeywords = new ArrayList<>();
            for (TopSearchAndClassificationBean.DataBean.SeaHotBean hotSearchBean : hotSearchList) {
                String hotName = hotSearchBean.getHotName();
                hotSearchKeywords.add(hotName);
            }
            TextOnlyTagAdapter<String> stringTextOnlyTagAdapter = new TextOnlyTagAdapter<>(mContext);
            mFtlHotSearch.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_NONE);
            mFtlHotSearch.setAdapter(stringTextOnlyTagAdapter);
            stringTextOnlyTagAdapter.appendData(hotSearchKeywords);
            mFtlHotSearch.setOnTagClickListener(new OnTagClickListener() {
                @Override
                public void onItemClick(FlowTagLayout parent, View view, int position) {
                    String hotSearchKeywordsSelected = hotSearchKeywords.get(position);
                    mEtSearchContent.setText(hotSearchKeywordsSelected);
                }
            });
        } else {
            // 如果热搜词列表为空 隐藏热搜标题和FlowTagLayout
            mTvHotSearchLabel.setVisibility(View.GONE);
            mFtlHotSearch.setVisibility(View.GONE);
        }

        //设置搜索分类
        List<TopSearchAndClassificationBean.DataBean.SearchConBean> searchCon = bean.getData().getSearchCon();
        List<SearchClassifiesBean> classifiesBeans = new ArrayList<>();
        for (int i = 0; i < searchCon.size(); i++) {
            TopSearchAndClassificationBean.DataBean.SearchConBean searchConBean = searchCon.get(i);
            String className = searchConBean.getClassName();
            String id = searchConBean.getId();
            SearchClassifiesBean searchClassifiesBean = new SearchClassifiesBean();
            searchClassifiesBean.setClassifyId(id);
            searchClassifiesBean.setClassifyName(className);
            searchClassifiesBean.setSelected(i == 0);
            classifiesBeans.add(searchClassifiesBean);
        }
        mClassifySelectedPosition = 0;
        mSearchClassificationDropMenuAdapter.appendData(classifiesBeans);
    }

    /**
     * 获取热搜词和分类失败，在此重新请求，超过五次后提示用户获取分类失败。
     *
     * @param throwable 异常信息
     */
    @Override
    public void getTopSearchAndClassificationError(Throwable throwable) {
        LogUtils.e(throwable.getMessage(), TAG);
    }

    @Override
    public void showSearchResult(IndexSearchListBean searchResultBean) {
        if (!searchResultBean.getData().getResult().isEmpty()) {
            mSearchResultAdapter.updateData(searchResultBean.getData().getResult());
            mScrollView.setVisibility(View.GONE);
            mTvSearchResultEmpty.setVisibility(View.GONE);
            mRvSearchResult.setVisibility(View.VISIBLE);
        } else {
            mSearchResultAdapter.clearData();
            mScrollView.setVisibility(View.GONE);
            mRvSearchResult.setVisibility(View.GONE);
            mTvSearchResultEmpty.setVisibility(View.VISIBLE);
        }
    }
}
